package org.example.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.erp.domain.ProcedureDetails;
import org.example.erp.domain.ProcedureProduct;
import org.example.erp.domain.ProcedureProductDom;
import org.example.erp.domain.Procedures;
import org.example.erp.mapper.ProceduresMapper;
import org.example.erp.service.ProcedureProductDomService;
import org.example.erp.service.ProcedureProductService;
import org.example.erp.service.ProceduresDetailsService;
import org.example.erp.service.ProceduresService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProceduresServiceImpl extends ServiceImpl<ProceduresMapper, Procedures> implements ProceduresService {

    @Autowired
    ProceduresDetailsService proceduresDetailsService;
    @Autowired
    ProcedureProductService procedureProductService;
    @Autowired
    ProcedureProductDomService procedureProductDomService;

    @Override
    public Procedures findDetails(String procedureCode) {
        return baseMapper.findDetails(procedureCode);
    }

    @Override
    @Transactional
    public boolean deleteDetails(List<String> ids) {
        boolean success = true;
        for (String id : ids) {
            int i = baseMapper.deleteById(id);
            if (i <= 0) {
                success = false; // 删除主记录失败
                break; // 可以选择继续尝试其他记录或立即返回
            }

            QueryWrapper<ProcedureDetails> q1 = new QueryWrapper<>();
            q1.lambda().eq(ProcedureDetails::getProcedureCode, id);
            boolean remove = proceduresDetailsService.remove(q1);
            if (!remove && proceduresDetailsService.count(q1) > 0) {
                success = false; // 存在记录但删除失败
                break; // 可以选择继续尝试其他记录或立即返回
            }

            QueryWrapper<ProcedureProduct> q2 = new QueryWrapper<>();
            q2.lambda().eq(ProcedureProduct::getProcedureCode, id);
            boolean remove1 = procedureProductService.remove(q2);
            if (!remove1 && procedureProductService.count(q2) > 0) {
                success = false; // 存在记录但删除失败
                break; // 可以选择继续尝试其他记录或立即返回
            }

            QueryWrapper<ProcedureProductDom> q3 = new QueryWrapper<>();
            q3.lambda().eq(ProcedureProductDom::getProcedureCode, id);
            boolean remove2 = procedureProductDomService.remove(q3);
            if (!remove2 && procedureProductDomService.count(q3) > 0) {
                success = false; // 存在记录但删除失败
                break; // 可以选择继续尝试其他记录或立即返回
            }
        }
        return success;
    }
}
